package com.spzx.channel.configure;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author GQS @Date 2024/10/13/9:19 @Description
 */
@Configuration
public class ThreadPoolConfig {
    /**
     * 配置线程池
     *
     * @return 返回一个初始化后的ThreadPoolExecutor实例
     */
    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        // 获取可用处理器的核心数
        int processorsCount = Runtime.getRuntime().availableProcessors();
        // 创建一个线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                processorsCount * 2, // 核心线程数，设置为处理器核心数的两倍
                processorsCount * 2, // 最大线程数，与核心线程数一致
                0, // 空闲线程存活时间，设置为0表示线程立即终止
                TimeUnit.SECONDS, // 时间单位
                new ArrayBlockingQueue<>(200), // 工作队列，用于保存等待执行的任务
                Executors.defaultThreadFactory(), // 线程工厂，用于创建新线程
                //new ThreadPoolExecutor.CallerRunsPolicy()
                //自定义拒绝策略
                (runnable, executor) -> {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    //再次将拒绝任务提交给线程池执行
                    executor.submit(runnable);
                }
        );
        // 预启动所有核心线程
        threadPoolExecutor.prestartAllCoreThreads();
        return threadPoolExecutor;
    }
}
